package likou.jindian;

import java.util.ArrayList;
import java.util.List;

public class  _02_05 {
    public static void main(String[] args) {

    }
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if(l1==null){
            return l2;
        }
        if(l2==null){
            return l1;
        }
        List<Integer> list1 = new ArrayList<>();
        List<Integer> list2 = new ArrayList<>();
        while(l1!=null){
            list1.add(l1.val);
            l1=l1.next;
        }
        while(l2!=null){
            list2.add(l2.val);
            l2=l2.next;
        }
        ListNode daan = new ListNode(-1);
        l1 = daan;
        List<Integer> tem = list1.size()>list2.size()?list1:list2;
        list2 = list1.size()<=list2.size()?list1:list2;
        list1 = tem;
        //下一位需要加的值
        int p=0;
        for(int i=0;i<list1.size();i++){
            int now = list1.get(i)+p;
            p=0;
            if(i<list2.size()){
                now+=list2.get(i);
            }
            if(now!=0&&now/10!=0){
                p=1;
                now-=10;
            }
            System.out.println(now);
            l1.next = new ListNode(now);
            l1 = l1.next;
        }
        if(p==1){
            l1.next = new ListNode(1);
        }
        return daan.next;
    }





    public ListNode addTwoNumbers2(ListNode l1, ListNode l2) {
        return solution2(l1, l2);
    }

    public ListNode solution2(ListNode l1, ListNode l2) {
        int pre = 0;
        ListNode preNode = new ListNode();
        ListNode tmpNode = preNode;
        while (l1 != null || l2 != null || pre > 0) {
            int sum = ((l1 == null) ? 0 : l1.val) + ((l2 == null) ? 0 : l2.val) + pre;
            tmpNode.next = new ListNode(sum % 10);
            tmpNode = tmpNode.next;
            pre = sum / 10;
            if (l1 != null) {
                l1 = l1.next;
            }
            if (l2 != null) {
                l2 = l2.next;
            }
        }
        return preNode.next;
    }


    public ListNode solution1(ListNode l1, ListNode l2) {
        int flag = 0;
        ListNode result = new ListNode();
        ListNode tmpNode = result;
        while (l1 != null || l2 != null || flag != 0) {
            int tmpSum = flag;
            tmpSum = tmpSum + ((l1 != null) ? l1.val : 0);
            tmpSum = tmpSum + ((l2 != null) ? l2.val : 0);
            flag = tmpSum / 10;
            tmpNode.next = new ListNode(tmpSum % 10);
            tmpNode = tmpNode.next;
            if (l1 != null) {
                l1 = l1.next;
            }
            if (l2 != null) {
                l2 = l2.next;
            }
        }
        return result.next;
    }
}
